from django.forms.models import modelformset_factory
from django.http import HttpRequest
from django.http import HttpResponseRedirect
from django import forms
from django.shortcuts import render_to_response

from webmapper.geophotos.forms import photo_forms
from webmapper.geophotos import models
from webmapper.geophotos import EXIF


def PhotoCRUD(request, photo_id):
  PhotoFormSet = modelformset_factory(models.GeoPhoto,
                                      fields=('title', 'media'))
  message = None
  if request.method == "POST":
    form = photo_forms.PhotoForm(request.POST, request.FILES)
    if form.is_valid():
      photo_obj = form.save(commit=False)
      print photo_obj.media.path
      
      photo_obj.save()
      f = open(photo_obj.media.path, 'rb')
      tags = EXIF.process_file(f)
      msg = "Taken: %s<br>\nMaker: %s" % (tags['EXIF DateTimeOriginal'],
                            tags['Image Model'])
      return render_to_response('status.html', {'message': request.POST["token"]})
    else: # return the form
      return render_to_response('photo_form.html', {'formset': form})
    
  elif request.method == "GET":
    # extract Photo ID and show the photo page
    
    # if no photo id, then show the form
    #form = photo_forms.PhotoForm()
    formset = PhotoFormSet()
    return render_to_response('photo_form.html', {'formset': formset,
                                                  'message' : message})